<?php
ob_start();

define('NL', "\n");
define('T', "\t");

class installer
{
	var $_version = '0.9.0';
	var $_step = 1;
	
	var $_db = false;
	var $_errors = array();
	
	function installer($step)
	{
		$method = 'step_'.$step;
		if(method_exists($this, $method)) {
			$this->_step = $step;
			$this->$method();
		} else {
			$this->step_1();
		}
	}

	function step_4()
	{
		$this->_header(4);
		$type		= $_POST['db_type'];
		$host		= $_POST['db_host'];
		$username	= $_POST['db_username'];
		$password	= $_POST['db_password'];
		$name		= $_POST['db_name'];
		$prefix		= $_POST['db_prefix'];
		$drop		= isset($_POST['opt_drop_tables']);
		$backup		= isset($_POST['opt_backup']);
		$sample		= isset($_POST['opt_sample']);
		// error check these variables
		if(empty($type) || !array_key_exists($type, $this->_db_types())) {
			$this->_errors['type'] = 'blah';
		}
		
		// host
		if(empty($host)) {
			$this->_errors['host'] = 'Required';
		}
		
		// username
		if(empty($username)) {
			$this->_errors['username'] = 'Required';
		}
		
		// password
		if(!empty($password)) {
		}
		
		// db name
		if(empty($name)) {
			$this->_errors['name'] = 'Required';
		}
		
		// prefix
		if(!empty($prefix)) {
			//$this->_errors['prefix'] 
		}
		
		if(!$this->_is_errors()) {
			// establish a connection to the db
			
			if($this->_db_connect($host, $username, $password)) {
				if($this->_db_exists($name)) {
					$select = $this->_db_select($name);
				} else {
					$select = $this->_db_create($name, true);
				}
				// make sure the db $name has been selected correctly before proceeding
				if($select) {
					// do we need to backup pre-existing tables?
					if($backup) {
						$this->_db_backup('backup.sql');
					}
					
					if(!$this->_is_errors()) {
					
						// do we need to drop existing tables?
						if($drop) {
							$this->_drop_tables();
						}
						// install schema and base data
						$this->_install_db();
						// do we need to install sample data
						if($sample) {
							$this->_sample_data();
						}
						return;
					}
				}
			}
		}
		// if we get to this point then something failed, display previous form and show any errors
		ob_clean();
		$this->step_3();
	}

	/**
	 * Display the form for database configuration
	 */
	function step_3()
	{
		$this->_header(3);
		if($this->_step == 3) {
			$type		= 'mysql';
			$host		= 'localhost';
			$username	= 'root';
			$password	= '';
			$name		= 'movies';
			$prefix		= 'mm_';
		} else {
			$type		= $_POST['db_type'];
			$host		= $_POST['db_host'];
			$username	= $_POST['db_username'];
			$password	= $_POST['db_password'];
			$name		= $_POST['db_name'];
			$prefix		= $_POST['db_prefix'];
		}
		print_r($this->_errors);
		?>
		<h2>Database Configuration</h2>
		<form method="post" action="index.php?step=4">
		<table border="1">
			<tr>
				<td>Database</td>
				<td>
					<select name="db_type">
						<?php
						foreach($this->_db_types() as $k=>$v) {
							if($type == $k) {
								echo '<option value="'.$k.'" selected="selected">'.$v.'</option>';
							} else {
								echo '<option value="'.$k.'">'.$v.'</option>';
							}
						}
						?>
					</select>
				</td>
			</tr>
			<tr>
				<td>Database Host Name</td>
				<td><input type="text" name="db_host" value="<?php echo $host; ?>" /></td>
			</tr>
			<tr>
				<td>Database User Name</td>
				<td><input type="text" name="db_username" value="<?php echo $username; ?>" /></td>
			</tr>
			<tr>
				<td>Database Password</td>
				<td><input type="text" name="db_password" value="<?php echo $password; ?>" /></td>
			</tr>
			<tr>
				<td>Database Name</td>
				<td><input type="text" name="db_name" value="<?php echo $name; ?>" /></td>
			</tr>
			<tr>
				<td>Database Table Prefix</td>
				<td><input type="text" name="db_prefix" value="<?php echo $prefix; ?>" /></td>
			</tr>
			<tr>
				<td></td>
				<td>
					<ul>
						<li><label><input type="checkbox" name="opt_drop_tables" value="1" />Drop Existing Tables</label></li>
						<li><label><input type="checkbox" name="opt_backup" value="1" />Backup Old Tables</label></li>
						<li><label><input type="checkbox" name="opt_sample" value="1" />Install Sample Data</label></li>
					</ul>
				</td>
			</tr>
		</table>
		<h2>Misc Settings</h2>
		<input type="submit" value="Next &gt;&gt;" />
		</form>
		<?php
	}

	/**
	 * Display the license agreement
	 */
	function step_2()
	{
		$this->_header(2);
		?>
		<iframe src="license.html" width="400" height="400" frameborder="1" scrolling="auto"></iframe>
		<div>
			<input type="button" value="Next &gt;&gt;" onclick="window.location = 'index.php?step=3';" />
		</div>
		<?php
		$this->_footer();
	}

	/**
	 * Display the pre-installation check
	 */
	function step_1()
	{

		$sp	= ini_get('session.save_path');
		$this->_header(1);
		?>
		<h2>Required Settings</h2>
		<p>If any of these items are highlighted in red then you must take actions to correct them before proceeding.</p>
		<p>Failure to do so may cause the installation to pre-maturely fail or cause Movie Manager 2005 to run incorrectly.</p>
		<table>
			<tr>
				<td>PHP Version >= 4.1.0</td>
				<td>
				<?php echo phpversion() < '4.1' ? '<span class="false">No</span>' : '<span class="true">Yes</span>'; ?>
				</td>
			</tr>
			<tr>
				<td>&nbsp; - zlib compression support</td>
				<td>
				<?php echo extension_loaded('zlib') ? '<span class="true">Available</span>' : '<span class="false">Unavailable</span>'; ?>
				</td>
			</tr>
			<tr>
				<td>&nbsp; - MySQL Support</td>
				<td>
				<?php echo function_exists('mysql_connect') ? '<span class="true">Available</span>' : '<span class="false">Unavailable</span>'; ?>
				</td>
			</tr>
			<tr>
				<td>configuation.php</td>
				<td>
				<?php
				if((file_exists('../configuration.php') && is_writable('../configuration.php')) || is_writable('../')) {
					echo '<span class="true">Writable</span>';
				} else {
					echo '<span class="false">Unwritable</span><br /><span class="small">You can still continue the installation. Just follow the instructions in the following steps to manually create your configuration.php file.</span>';
				}
				?>
				</td>
			</tr>
			<tr>
				<td>Session Save Path</td>
				<td>
				<?php echo is_writable($sp) ? '<span class="true">Writable</span>' : '<span class="false">Unwriteable</span>'; ?>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<?php echo $sp ? $sp : 'Not set'; ?>
				</td>
			</tr>
		</table>
		<h2>Version Check</h2>
		<p>Make sure that your installing the latest version of Movie Manager</p>
		<p>More information can be found at <a href="http://www.pelicansareevil.com/mm/" target="_blank">www.pelicansareevil.com/mm/</a>
		<?php
		$security = array();
		if(ini_get('register_globals') == '1') {
			$security[] = 'PHP register_globals setting is `ON` instead of `OFF`';
		}

		if(count($security) > 0) {
			?>
			<h2>Security Check</h2>
			<p>Following PHP Server Settings are not optimal for <strong>Security</strong> and it is recommended to change them:</p>
			<ul>
			<?php
				foreach($security as $txt) {
					echo '<li>'.$txt.'</li>';
				}
			?>
			</ul>
			<?php
		}
		?>
		<h2>Recommended Settings Check</h2>
		<p>These settings are recommended for PHP in order to ensure full compatibility with Movie Manager.</p>
		<p>However, Movie Manager will still operate if your settings do not match the recommended settings below.</p>
		<table>
		<tr>
			<th>Directive</th>
			<th>Recommended</th>
			<th>Actual</th>
		</tr>
		<?php
		$php_recommended_settings = array(array ('Safe Mode','safe_mode','OFF'),
							array ('Display Errors','display_errors','ON'),
							array ('File Uploads','file_uploads','ON'),
							array ('Magic Quotes GPC','magic_quotes_gpc','ON'),
							array ('Magic Quotes Runtime','magic_quotes_runtime','OFF'),
							array ('Register Globals','register_globals','OFF'),
							array ('Output Buffering','output_buffering','OFF'),
							array ('Session auto start','session.auto_start','OFF')
		);
		foreach($php_recommended_settings as $phprec) {
			?>
			<tr>
				<td><?php echo $phprec[0]; ?></td>
				<td><?php echo $phprec[2]; ?></td>
				<td>
					<strong>
					<?php
					if($this->_get_php_setting($phprec[1]) == $phprec[2]) {
						echo '<span class="true">';
					} else {
						echo '<span class="false">';
					}
					echo $this->_get_php_setting($phprec[1]);
					?>
					</span>
					</strong>
				</td>
			</tr>
			<?php
		}
		?>
		</table>
		<h2>Directory and File Permissions Check</h2>
		<p>In order for Movie Manager to function correctly it needs to be able to access or write to certain files or directories.</p>
		<p>If you see "Unwriteable" you need to change the permissions  on the file or directory to allow Movie Manager to write to it.</p>

		<table>
		<?php
		$writeable		= '<span class="true">Writeable</span>';
		$unwriteable	= '<span class="false">Unwriteable</span>';
		$paths = array('cache', 'imdb_images', 'templates_c', 'templates');
		foreach($paths as $dir) {
			echo '<tr>';
			echo '<td>'.$dir.'</td>';
			echo '<td>';
			echo is_writable('../'.$dir) ? $writeable : $unwriteable;
			echo '</td>';
			echo '</tr>';
		}
		?>
		</table>
		<input type="button" value="Next &gt;&gt;" onclick="window.location = 'index.php?step=2';" />
		<input type="button" value="Check Again" onclick="window.location = window.location;" />
		<?php
		$this->_footer();
	}

	function _header($step)
	{
		$steps = array();
		$steps[] = 'Pre-Installation Check';
		$steps[] = 'License';
		$steps[] = 'Database Configuration';
		$steps[] = 'Write Database';
		include 'templates/header.php';
	}

	function _is_errors()
	{
		return (count($this->_errors) > 0);
	}
	
	function _footer()
	{
		include 'templates/footer.php';
	}

	function _get_php_setting($val)
	{
		$r	= (ini_get($val) == '1' ? 1 : 0);
		return $r ? 'ON' : 'OFF';
	}

	function _db_connect($server, $username, $password)
	{
		$db = @mysql_connect($server, $username, $password);
		if($db) {
			$this->_db = $db;
			return true;
		} else {
			$this->_errors[] = 'Unable to connect to db. '.mysql_error();
		}
		return false;
	}
	
	function _db_select($name)
	{
		if($this->_db) {
			$db = @mysql_select_db($name, $this->_db);
			if($db) {
				return true;
			} else {
				$this->_errors[] = 'Unable to select db. '.mysql_error();
			}
		} else {
			$this->_errors[] = 'Unable to select db. Connection to database not established';
		}
		return false;
	}
	
	function _db_create($name, $select = true)
	{
		$sql	 = "CREATE DATABASE IF NOT EXISTS `".$name."`";
		$result	= mysql_query($sql);
		if($result) {
			// we have created a new db!
			if($select) {
				if($this->_db_select($name)) {
					return true;
				}
			} else {
				return true;
			}
		}
		return false;
	}
	
	function _db_exists($name)
	{
		$sql	= "SHOW DATABASES LIKE '".$name."'";
		$result	= mysql_query($sql);
		if(mysql_num_rows($result) == 1) {
			return true;
		}
		return false;
	}
	
	function _db_types()
	{
		return array('mysql' => 'MySQL');
	}
	
	function _db_backup($save_to)
	{
		set_time_limit(0);
		if(!file_exists($save_to)) {
			if(!touch($save_to, 0777)) {
				$this->_errors[] = 'Unable to create backup file '.$save_to;
				return false;
			}
		}
		
		if(!$this->_fh_open_write($save_to, 'wb')) {
			$this->_errors[] = 'Unable to open the backup file ('.$save_to.') for writing.';
			return false;
		}

		$this->_fh_write('# DB Backup'.NL);
		$this->_fh_write('# Generation Time: '.date('Y-m-d H:i:s').NL);
		
		$sql	= "SHOW TABLES;";
		$result	= mysql_query($sql, $this->_db);
		
		if(mysql_num_rows($result) > 0) {
			// loop through each table
			while(list($table_name) = mysql_fetch_row($result)) {
				$this->_fh_write('#'.NL.'# Dumping data for `'.$table_name.'`'.NL.'#'.NL);
				$this->_fh_write('DROP TABLE IF EXISTS `'.$table_name.'`;'.NL.NL);
			}
		} else {
			// nothing to backup!
			$this->_fh_write(NL.'# no tables to backup');
		}
		$this->_fh_close();
		
		return true;
	}
	
	function _fh_open_write($path)
	{
		if(file_exists($path) && is_writeable($path)) {
			if(($fh = fopen($path, 'wb')) != false) {
				$this->_fh_mode = 'write';
				$this->_fh = $fh;
				return true;
			}
		}
		return false;
	}
	
	function _fh_write($data)
	{
		if($this->_fh) {
			if(!empty($data)) {
				if(!fwrite($this->_fh, $data, strlen($data))) {
					return true;
				}
			} else {
				return true;
			}
		}
		return false;
	}
	
	function _fh_close()
	{
		if($this->_fh) {
			return fclose($this->_fh);
		}
		return false;
	}
}

?>